# -*- coding: utf-8 -*-
from scrapy.utils.project import get_project_settings
from zc_core.client.mongo_client import Mongo


class SpuPoolDao(object):
    """
    商品池操作简易封装（Mongo）
    """

    # hash查询全量列表
    def get_spu_batch_list(self, batch_no):
        spu_id_list = list()
        items = Mongo().list('spu_{}'.format(batch_no), query={}, fields={'_id': 1})
        for it in items:
            spu_id_list.append(it.get('_id'))

        return spu_id_list

    # hash查询全量列表
    def get_spu_pool_list(self, fields={'_id': 1, 'spuId': 1, 'batchNo': 1, 'offlineTime': 1}, query={}):
        settings = get_project_settings()
        max_offline_time = settings.get('MAX_OFFLINE_TIME', 1)
        query['offlineTime'] = {'$lte': max_offline_time}

        return Mongo().list('spu_pool', query=query, fields=fields)

    # 更新下线批次数
    def update_offline(self, batch_no):
        off_rs = Mongo(batch_no=batch_no).update('spu_pool', {'batchNo': {'$lte': batch_no}}, {'$inc': {'offlineTime': 1}}, multi=True)
        return off_rs

    # 更新下线商品
    def del_offline(self, batch_no, keys):
        return Mongo(batch_no=batch_no).update('spu_pool', {'batchNo': {'$ne': batch_no}}, {'$inc': {'offlineTime': 1}})
